/*
 * TCSS 558
 * Distributed HashMap
 * Fall 2013
 * James Marquardt
 * Matt Adams
 * Justin Wong
 */
package node.tasks;

import static com.google.common.base.Preconditions.checkNotNull;

import java.util.Random;

import model.NodeReferences;
import node.Node;
import node.NodeActual;

/**
 * @author Justin Wong
 */
public class FixFingerTable implements Runnable {
	
    /**
     * Random number generator for randomly picking another finger to fix.
     */
    private Random random = new Random();
    
	  /**
     * Actual node performing stabilize.
     */
    private NodeActual node;
    
    /**
     * References for node performing stabilize.
     */
    private NodeReferences references;
    
    /**
     * Constructs FixFingerTable object.
     * 
     * @param node Node to have finger table fixed.
     * @param references Node references.
     * @param entries Node entries.
     */
	public FixFingerTable(NodeActual node, NodeReferences references){
        this.node = checkNotNull(node);
        this.references = checkNotNull(references);
	}
	

    @Override
    public void run() {       
        int m_value = references.getMValue();
        int nodeID = node.getNodeID();
        int total_size = (int) Math.pow(2, m_value);
        int fingerToFix = this.random.nextInt(total_size);
        int key = (nodeID + fingerToFix) % total_size;
        Node nextNode = this.node.findSuccessor(key);
        if (nextNode != null && !this.references.containsReference(nextNode)) {
            this.references.addReference(nextNode);
        }
    }
}
